import React, { useEffect, useState } from 'react'
import Navbar from '../../../compounts/navber/Navbar'
import { Button, SearchBar, Space, Toast, Avatar, InfiniteScroll } from 'antd-mobile'
import { RightOutline } from 'antd-mobile-icons'
import request from '../../../api/request'
import style from './doctor.module.css'
import { useNavigate } from 'react-router-dom'

function Index() {
    const nav = useNavigate()
    // 疾病数据
    const [jibinglist] = useState([
        '高血压', '糖尿病', '儿科', '痛风', '风湿病', '心血管内科', '消化内科'
    ])
    // 医生数据
    // const [doctorlist, setDoctorlist] = useState([])
    // 科室数据
    const [deptlist, setDeptlist] = useState([])
    // 科室对应的病症数据
    const [diseaseByDept, setDiseaseByDept] = useState({})
    // 加载状态
    const [loading, setLoading] = useState(true)

    // 查询医生列表
    const getdoctorlist = (page) => {
        console.log('请求医生列表，页码:', page);
        return request.get('/user/inquiry/v1/findDoctorList', {
            params: {
                deptId: 2,
                condition: 1,
                page: page ? page : 1,
                count: 10
            }
        }).then((res) => {
            console.log('医生列表接口返回:', res.data);
            return res.data.result || [];
        }).catch((error) => {
            console.error('请求医生列表失败:', error);
            return [];
        });
    }

    // 查询科室列表
    const getkeshi = () => {
        request.get('/share/knowledgeBase/v1/findDepartment').then((res) => {
            // 只获取前四条数据
            const arr = (res.data.result || []).slice(0, 4)
            setDeptlist(arr)
            // 获取每个科室的病症
            arr.forEach(dept => {
                getDiseaseByDept(dept.id)
            })
            setLoading(false)
        })
    }

    // 根据科室ID查询病症
    const getDiseaseByDept = (deptId) => {
        // 改回GET方法
        request.get('/share/knowledgeBase/v1/findDiseaseCategory', {
            params: {
                departmentId: deptId  // 确保参数名为小写
            }
        }).then((res) => {
            console.log(`科室ID ${deptId} 的病症数据:`, res.data);
            setDiseaseByDept(prev => ({
                ...prev,
                [deptId]: res.data.result
            }))

        });
    }

    // 跳转到全部科室页面
    const goToAllDepartments = () => {
        nav('/allDepartments')
    }

    // 无限滚动
    // 数据存储
    const [data, setData] = useState([])
    const [page, setPage] = useState(0) // 从第0页开始，与 keshidoctor 保持一致
    const [loadingMore, setLoadingMore] = useState(false) // 添加加载状态
    const [hasMore, setHasMore] = useState(true)
    async function loadMore() {
        if (loadingMore) return; // 防止重复加载
        console.log('触发 loadMore，当前页码:', page, 'hasMore:', hasMore);
        
        // 添加状态
        setLoadingMore(true);
        try {
            const newPage = page + 1;
            console.log('请求第', newPage, '页数据');
            
            const newData = await getdoctorlist(newPage);
            console.log('第', newPage, '页返回数据:', newData);
            
            if (newData && newData.length > 0) {
                setData(val => [...val, ...newData]);
                setPage(newPage);
                // 如果返回的数据少于每页数量，说明没有更多数据了
                if (newData.length < 10) {
                    setHasMore(false);
                    console.log('数据不足10条，设置 hasMore 为 false');
                }
            } else {
                setHasMore(false);
                console.log('返回数据为空，设置 hasMore 为 false');
            }
        } catch (error) {
            Toast.show('加载失败，请重试');
            console.error('加载更多医生数据失败:', error);
        } finally {
            setLoadingMore(false);
            console.log('loadMore 完成，当前页码:', page, 'hasMore:', hasMore);
        }
    }

    useEffect(() => {
        // 加载第一页数据
        const loadFirstPage = async () => {
            try {
                const firstPageData = await getdoctorlist(1);
                if (firstPageData && firstPageData.length > 0) {
                    setData(firstPageData);
                    // 如果第一页数据少于10条，说明没有更多数据
                    if (firstPageData.length < 10) {
                        setHasMore(false);
                    }
                } else {
                    setHasMore(false);
                }
            } catch (error) {
                Toast.show('加载失败，请重试');
                console.error('加载医生数据失败:', error);
            }
        };

        loadFirstPage();
        getkeshi();
    }, [])

    if (loading) {
        return <div className={style.loading}>加载中...</div>
    }

    // 点击去往医生详情页
    const DoctorClick = (id) => {
        nav(`/doctorDetail?id=${id}`)
    }

    return (
        <div className={style.box}>
            <Navbar title={'快速找医生'}></Navbar>
            <SearchBar style={{ '--border-radius': '50px' }} placeholder='疾病|医院|医生' />
            {/* 疾病找医生 */}
            <div className={style.jibingbox}>
                <div className={style.title}>
                    <span>按疾病找医生</span>
                    <span className={style.all}>全部疾病<RightOutline /></span>
                </div>
                <ul className={style.historyinner}>
                    {jibinglist.map((item, index) => (
                        <li className={style.historyitem} key={index}>{item}</li>
                    ))}
                </ul>
            </div>
            {/* 科室找医生 */}
            <div className={style.jibingbox}>
                <div className={style.title}>
                    <span>按科室找医生</span>
                    <span className={style.all} onClick={goToAllDepartments}>全部科室<RightOutline /></span>
                </div>
                <div className={style.keshibox}>
                    {deptlist.map((item, index) => (
                        <div className={style.keshiinner} key={index} onClick={() => nav(`/keshiDoctor?id=${item.id}&name=${item.departmentName}`)}>
                            <div className={style.keshipic}>
                                <Avatar src={item.pic} style={{ '--size': '36px' }} />
                                <div className={style.keshiName}>{item.departmentName}</div>
                            </div>

                            <div className={style.diseaseList}>
                                {diseaseByDept[item.id]?.map((disease, idx) => (
                                    <div key={idx} className={style.diseaseItem}>
                                        <span>{disease.name}、</span>
                                    </div>
                                )) || <div className={style.noData}>暂无数据</div>}
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* 热门医生 */}
            <div className={style.doctorbox}>
                <div className={style.hotdoctor}>热门医生</div>
                {data.length > 0 ? (
                    data.map((item, index) => (
                        <div className={style.doctorlist} key={index} onClick={() => DoctorClick(item.doctorId)}>
                            <div><Avatar src={item.imagePic} style={{ '--size': '64px', '--border-radius': '50px' }} /></div>
                            <div className={style.jiasao}>
                                <h5 className={style.name}>{item.doctorName} {item.jobTitle}</h5>
                                <p className={style.yiyuan}>{item.inauguralHospital}</p>
                                <div className={style.shanchang}>
                                    擅长：{item.specialty || '擅长治疗颅内动脉肿瘤、脑和脊髓血管畸形、颈动脉海绵溃缩、硬化等'}
                                </div>
                            </div>
                        </div>
                    ))
                ) : (
                    <div className={style.noData}>暂无医生数据</div>
                )}
                {/* 无限滚动 */}
                <InfiniteScroll 
                    loadMore={loadMore} 
                    hasMore={hasMore}
                    threshold={100}
                >
                    {loadingMore && (
                        <div className={style.loadingMore}>
                            加载中...
                        </div>
                    )}
                    {!hasMore && !loadingMore && (
                        <div className={style.noMoreData}>
                            没有更多数据了
                        </div>
                    )}
                </InfiniteScroll>
            </div>
        </div>
    )
}

export default Index
